// pages/noticePreview/noticePreview.js
let messageContentTemplate = require('../../template/messageContent/messageContent.js')
let exportEmailModelTemplate = require('../../template/exportEmailModal/exportEmailModal.js')
let klassModel = require('../../models/klass.js')
let getNoticeOperation = require('../../operation/getNoticeOperation.js')
let bxt = require('../../utils/bxt.js')
let noticeModel = require('../../models/notice.js')
let receiptModel = require('../../models/receipt.js')
let request = require('../../operation/operation.js')
let activateKlass = false

let klasses = null, notice = null,klass = null // 绑定班级介绍界面传过来

Page({

  /**
   * 页面的初始数据
   */
  data: {
    notice:{},
    edit:true,
    activateKlass:activateKlass,
    actionsheet: {
     
    }
  },

  /**
   * 生命周期函数--监听页面加载
   * options: activateKlass 自动绑定班级时传过来
   */
  onLoad: function (options) {
    if (options.activateKlass) {
      activateKlass = true
      this.setData({
          activateKlass:activateKlass
      })
    }
    if (getApp().globalData.param.notice) {
      notice = getApp().globalData.param.notice
    }else {
      notice = getApp().globalData.param
    }
    
    if (getApp().globalData.param.klass) {
      klass = getApp().globalData.param.klass
    }
    messageContentTemplate.initMessageContentView(this, notice, activateKlass)
    this.getNotice()
    this.initActionSheetActions()
    
    wx.showShareMenu({
      withShareTicket: true
    })
    wx.hideShareMenu()

    getApp().notificationCenter.register(bxt.REFRESH_NOTICE_MESSAGE, this, "getNotice")
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    klass = null
    notice = null
    activateKlass = false
    getApp().notificationCenter.remove(bxt.REFRESH_NOTICE_MESSAGE, this)
  },

  /**
   * 分享事件处理函数
   */
  onShareAppMessage:function(options) {   
    this.setData({
      ['actionsheet.show']: false
    });
     
    let tmpklass
    if (null != klass) {
      tmpklass = klass
    }else {
      tmpklass = klasses[options.target.dataset.index]
    }
         
    // if (101 == notice.category && (tmpklass.wxGroupUid == null || tmpklass.wxGroupUid == '') && activateKlass == true) {  // 激活班级通知
    //   return noticeModel.showActivateClass(this, tmpklass, options,true)
    // }else {
      let that = this, isBindClass = true
      for (let index = 0, length = notice.receiptStatus.length; index < length; index++) {  // 检查是否需要绑定通知和班级的关系
        if (notice.receiptStatus[index].klassSid == tmpklass.sid) {
          isBindClass = false;
          break
        }
      }
      
      return noticeModel.shareMessageToWeXin(this, options, notice, tmpklass.sid, isBindClass, function () {
        if (true == isBindClass) {
          that.getNotice()
        }
      })    
    // }
    
  },

  onShowReceiptList: function (event) {
    let notice = this.data.notice
    notice.klass = event.currentTarget.dataset.klass // 为了下个界面获取到班级信息
    notice.klass.sid = notice.klass.klassSid

    getApp().globalData.param = { 'notice': notice }

    wx.navigateTo({
      url: '../receiptList/receiptList?noticeSid=' + this.data.notice.sid,
    })
  },

  /**
   * 点击修改通知事件处理函数
   */
  // onShowEditMessage:function() {
  //   getApp().globalData.param = this.data.notice
  //   wx.navigateTo({
  //     url: '../editNotice/editNotice',
  //   })
  // },

  /**
   * 点击更多按钮事件处理函数
   */
  onMore:function() {
    let that = this

    wx.showActionSheet({
      itemList: ['修改通知','删除通知'],
      success: function(res) {
        if (0 == res.tapIndex) {
          getApp().globalData.param = that.data.notice
          wx.navigateTo({
            url: '../editNotice/editNotice',
          })
        }else if (1 == res.tapIndex) {
          wx.showModal({
            title: '删除通知',
            content: '确定删除这条通知吗？',
            showCancel: true,            
            success: function(res) {
              if (true == res.confirm) {
                that.deleteNotice()
              }              
            }            
          })
        }
      }     
    })
  },

  /**
   * 通知内容模板会调用
   */
  previewImage:function(event) {
    messageContentTemplate.previewImage(event.currentTarget.dataset.path.url, receiptModel.getImagesUrl(this.data.notice.imagesArray))
  },

  /**
   * 点击选择班级分享按钮事件处理函数
   */
  onShowActionSheet:function() {
    this.setData({
      'actionsheet.show': true
    })
  },

  _handleZanActionsheetCancelBtnClick: function ({ componentId }) {
    this.setData({
      ['actionsheet.show']: false
    });
  },

  _handleZanActionsheetMaskClick: function ({ componentId }) {
    this.setData({
      ['actionsheet.show']: false
    });
  },

  /**
   * 初始化actionSheet
   */
  initActionSheetActions:function() {
    klasses = klassModel.getAllKlassUIData()
    let result = []
    for (let index = 0,length = klasses.length; index < length; index++) {
      result.push({
        name: '分享到 ' + klasses[index].schoolName + ' · ' + klasses[index].uiname + ' 聊天群',
        className: 'action-class',
        loading: false,
        openType: 'share'})
    }

    this.setData({
      actionsheet: {
      show: false,
      cancelText: '关闭',
      actions: result
    }})

    return result
  },

  /**
   * 显示输入邮箱对话框
   */
  showInputEmailDialog: function (event) {
    exportEmailModelTemplate.show(event.currentTarget.dataset.klass.klassSid)
  },

  onCancel:function() {
    exportEmailModelTemplate.cancel()
  },

  /**
   * 邮箱输入框输入事件处理函数
   */
  bindKeyInput: function (event) {
    exportEmailModelTemplate.setEmail(event.detail.value)
  },

  onConfirm:function(event) {
    exportEmailModelTemplate.confirm()
  },

  /**
   * 获取通知详情
   */
  getNotice:function() {
    let that = this
    getNoticeOperation.getNotice(notice.sid)
      .then(res => { 
        if (res.receiptStatus && 0 < res.receiptStatus.length) {
          let receiptStatus
          for (let index = 0, length = res.receiptStatus.length; index < length; index++) {
            receiptStatus = res.receiptStatus[index].currentStatus.split('/');
            res.receiptStatus[index].receipt = receiptStatus[0];
            res.receiptStatus[index].noReceipt = receiptStatus[1] - receiptStatus[0];
          }          
        }
       
        notice = res
        messageContentTemplate.initMessageContentView(that, notice, activateKlass)
        exportEmailModelTemplate.init(that,notice)
      })
  },

  /**
   * 删除通知事件处理函数
   */
  deleteNotice:function() {
    let that = this
    wx.showLoading({
      title: '请稍等',
      mask: true
    })
    
    request.deleteRequest('/notices/' + notice.sid, {}, true)
      .then(res => {
        wx.hideLoading()
        var data = res.data;
        if (request.SUCCESSED == data.status) {                    
          noticeModel.handleDeleteNotice(notice)
          getApp().notificationCenter.post(bxt.DELETE_NOTICE_MESSAGE)
          getApp().autoBack('删除成功')
        } else {
          wx.showToast({
            title: data.msg,
            iocn: 'none'
          })
        }
      })
      .catch(e => {
        wx.hideLoading()        
      })
  }
  
})